package com.zdlyh.service.impl;

import com.zdlyh.domain.MinioProperties;
import com.zdlyh.domain.ResponseResult;
import com.zdlyh.enums.AppHttpCodeEnum;
import com.zdlyh.exception.SystemException;
import com.zdlyh.service.MinioService;
import com.zdlyh.utils.PathUtils;
import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.MinioException;
import io.minio.http.Method;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @Author liuYuhui
 * @Date 2023/7/6 13:34
 */
@Service
@RequiredArgsConstructor
public class MinioServiceImpl implements MinioService {

    private final MinioClient minioClient;

    private final MinioProperties minioProperties;

    @Override
    public ResponseResult uploadImg(MultipartFile file) {
        try {
            // 1、判断文件类型 只能是png类型的文件
            String originalFilename = file.getOriginalFilename(); // 获取文件的原始文件名
            if (!originalFilename.endsWith(".png")){
                throw new SystemException(AppHttpCodeEnum.File_Type_Error);
            }

            // 删除原来的头像
            /*Long userId = SecurityUtils.getUserId();
            User user = userMapper.selectById(userId);
            String avatar = user.getAvatar();
            String substring = avatar.substring(avatar.indexOf("sumeng-blog/") + "sumeng-blog/".length());
            RemoveObjectArgs removeObjectArgs = RemoveObjectArgs.builder().bucket(bucket)
                    .object(substring).build();
            minioClient.removeObject(removeObjectArgs);*/

            // 使用UUID替换原来的文件名称,用日期拼接成文件夹路径(2023/7/7/UUID.png)
            String fileName = PathUtils.generateFilePath(originalFilename);

            // 2、文件上传：上传文件流
            try (InputStream in = file.getInputStream()){
                PutObjectArgs putObjectArgs = PutObjectArgs.builder().bucket(minioProperties.getBucket()).object(fileName)
                        .contentType(file.getContentType())
                        .stream(in, file.getSize(), -1)
                        .build();
                minioClient.putObject(putObjectArgs);
            }

            // 3、获取文件临时http url
            GetPresignedObjectUrlArgs presignedObjectUrlArgs = GetPresignedObjectUrlArgs.builder()
                    .bucket(minioProperties.getBucket())
                    .object(fileName) // object的路径
                    .method(Method.GET) // http请求方式
                    //.expiry(5, TimeUnit.MINUTES) // url过期时间
                    .build();
            String url = minioClient.getPresignedObjectUrl(presignedObjectUrlArgs);

            // 4、获取文件http url并去除后面令牌验证，然后返回
            int pngIndex = url.lastIndexOf(".png");
            if (pngIndex != -1) {
                String subUrl = url.substring(0, pngIndex + 4);
                System.out.println(subUrl);
                return ResponseResult.okResult(subUrl);
            } else {
                System.out.println("URL does not contain '.png'");
            }

        } catch (MinioException e) {
            System.out.println("Error occurred: " + e);
            System.out.println("HTTP trace: " + e.httpTrace());
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        }
        return null;
    }
}
